/*
 * Guid.java
 *
 * Created on September 13, 2006, 11:25 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package finalintex2web;
import java.net.InetAddress;
import java.lang.*;
import java.net.InetAddress;
import java.util.Random;


/**
 * GUID generator
 * @author craig marshall
 */
public class GUID {
    
    private static long lasttime;
    private static long counter;
    static String guid;
    static long temp = 0;
    static String pad = ""; 
    static String[] stringArray;
    static String ip = "";
    static  Random rand = new Random();
    
  
    /** Creates a new instance of Guid */
    public GUID() {
    }
    /** generates a new GUID 
     * @return GUID
     *
     */
    public static synchronized String generate(){
        try{
        // Random dumber addition
        guid =  (rand.nextInt(9999) + "-");
        //catch the system time in millisecs    
        long now = System.currentTimeMillis();
        guid += Long.toHexString(now); 
        temp = guid.length();
        
    
        //pad the hex time
        for (int i=0; i < (16 - temp); i++)
        {
            guid =("0" + guid);
        }
     
        //increment the counter
        if(now == lasttime)
        {
            counter ++;
        
            if(counter > 16777215)
            Thread.sleep(1);
            counter = 0;
            now = System.currentTimeMillis();
        }
        else 
        {
            counter = 0;
        }  
    
        //pad the counter with zeros.
        pad = Long.toHexString(counter);
        temp = pad.length();
        for(int i = 1; i < (7-temp); i++)
        {
            pad =( "0" + pad);
        } 
        guid = (guid + pad);
    
        //get host address and put in into a string array.
        ip = java.net.InetAddress.getLocalHost().getHostAddress();
        stringArray = ip.split("\\.");
     
        //convert ip to hex and add to guid
        for(int i = 0; i <= 3; i++)
        {
         
            temp = Long.decode(stringArray[i]);
            pad = Long.toHexString(temp);
                if (pad.length() < 2)
                {
                    pad += 0;
                }
        
            guid += pad;
        }
    
        lasttime = now;
        }catch(Exception e){ }
    return guid;
    
    
    }
}
    

